import XLSX from 'xlsx';

function autoWidthFunc(ws, data) {
  // set worksheet max width per col
  const colWidth = data.map((row) =>
    row.map((val) => {
      // if null/undefined
      if (val == null) {
        return { wch: 10 };
      } else if (val.toString().charCodeAt(0) > 255) {
        // if chinese
        return { wch: val.toString().length * 2 };
      } else {
        return { wch: val.toString().length };
      }
    })
  );
  // start in the first row
  const result = colWidth[0];
  for (let i = 1; i < colWidth.length; i++) {
    for (let j = 0; j < colWidth[i].length; j++) {
      if (result[j].wch < colWidth[i][j].wch) {
        result[j].wch = colWidth[i][j].wch;
      }
    }
  }
  ws['!cols'] = result;
}

function jsonToArray(key, jsonData) {
  return jsonData.map((v) =>
    key.map((j) => {
      return v[j];
    })
  );
}

//....
const exportArrayToExcel = (arr, PCAllData) => {
  downloadExl(arr, PCAllData);
};
//如果使用 FileSaver.js 就不要同时使用以下函数
function saveAs(obj, fileName) {
  //当然可以自定义简单的下载文件实现方式
  var tmpa = document.createElement('a');
  tmpa.download = fileName || '下载';
  tmpa.href = URL.createObjectURL(obj); //绑定a标签
  tmpa.click(); //模拟点击实现下载
  setTimeout(function() {
    //延时释放
    URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
}
const wopts = { bookType: 'xlsx', bookSST: true, type: 'binary' }; //这里的数据是用来定义导出的格式类型
function downloadExl({ arr, PCAllData, summaryType }) {
  var wb = {
    SheetNames: arr.map((item) => {
      return item.name;
    }),
    Sheets: {},
    Props: {},
  };
  console.log('PCAllData', PCAllData);
  let sheetArr = arr.filter((item) => {
    return !item.children;
  });
  //wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通过json_to_sheet转成单页(Sheet)数据

  // data["B1"] = { t: "s", v: "asdad" };

  sheetArr.map((item) => {
    let data = [];
    let col = 'C';
    let i = 2;
    let str = summaryType === '0' ? '系统类型' : '楼层';
    let keyStr = item.elementId + '_' + summaryType;

    // 遍历数据
    PCAllData[keyStr].group.map((item) => {
      console.log('item', item);
      let obj = {};
      obj[str] = PCAllData[keyStr].elementTypeName;
      data.push(obj);
      obj[str] = item.groupName;
      data.push(obj);
      item.quantity.map((val) => {
        val.teamQuantitys.map((ei) => {
          data[i++] = {};
          if (data[i - 2][str] !== val.teamName) {
            data[i - 1][str] = val.teamName;
          }
          // console.log('val', val);
          data[i - 1]['构件名称'] = ei.elementName;
          // console.log('ei', ei);

          Object.keys(ei.quantity).forEach((ej) => {
            // console.log('ej', ej);

            data[i - 1][ej] = ei.quantity[ej];
          });
        });
      });
      data[i++] = item.groupSum.teamQuantitys[0].quantity;
      data[i - 1]['构件名称'] = '合计';
      i++; //合计后
    });
    console.log('data', data);
    // 转换表格数据
    data = XLSX.utils.json_to_sheet(data);
    data['A1'] = { t: 's', v: str };
    data['B1'] = { t: 's', v: '构件名称' };
    // 设置表头
    PCAllData[keyStr].fields.map((item, index) => {
      console.log('dd', String.fromCharCode(col.charCodeAt() + index) + 2);

      data[String.fromCharCode(col.charCodeAt() + index) + 2] =
        data[String.fromCharCode(col.charCodeAt() + index) + 1];
    });
    data['C1'] = { t: 's', v: '工程量名称' };
    data['!merges'] = [
      {
        //合并第一行数据[B1,C1,D1,E1]
        s: {
          //s为开始
          c: 0, //开始列
          r: 0, //开始取值范围
        },
        e: {
          //e结束
          c: 0, //结束列
          r: 1, //结束范围
        },
      },
      {
        s: { c: 1, r: 0 },
        e: { c: 1, r: 1 },
      },
    ];
    data['!merges'].push({
      s: { c: 2, r: 0 },
      e: { c: PCAllData[keyStr].fields.length + 1, r: 0 },
    });
    // 保存到页签
    wb.Sheets[item.name] = data;
  });

  // autoWidthFunc(ws, arr);
  saveAs(
    new Blob([s2ab(XLSX.write(wb, wopts))], {
      type: 'application/octet-stream',
    }),
    '安装统计表' +
      new Date().getTime() +
      '.' +
      (wopts.bookType == 'biff2' ? 'xls' : wopts.bookType)
  );
}
function s2ab(s) {
  if (typeof ArrayBuffer !== 'undefined') {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  } else {
    var buf = new Array(s.length);
    for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }
}

// const exportArrayToExcel2 = ({ key, data, title, filename, autoWidth }) => {
//   var elt = document.getElementsByClassName('el-table')[0];
//   console.log('elt', elt);

//   var wb = XLSX.utils.table_to_book(elt, { sheet: 'Sheet JS' });
//   // return
//   XLSX.writeFile(wb, 'SheetJSTableExport.' + 'xlsx');

//   // // const sheet1 = XLSX.utils.json_to_sheet(sheetData1);
//   // const wb = XLSX.utils.book_new();

//   // // XLSX.utils.book_append_sheet(wb, sheet1, '收件人列表');

//   // const arr = jsonToArray(key, data);
//   // arr.unshift(title);
//   // const ws = XLSX.utils.aoa_to_sheet(arr);
//   // if (autoWidth) {
//   //   autoWidthFunc(ws, arr);
//   // }
//   // XLSX.utils.book_append_sheet(wb, ws, filename);
//   // XLSX.utils.book_append_sheet(wb, ws, "filename");
//   // XLSX.writeFile(wb, filename + ".xlsx");
// };

export default {
  exportArrayToExcel,
};
